﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Yahoo.Yui.Compressor;

namespace Compressor.View
{
    /// <summary>
    /// CssFolder.xaml 的交互逻辑
    /// </summary>
    public partial class JavaScriptFolder : Window
    {
        public JavaScriptFolder()
        {
            InitializeComponent();
        }
        public string[] FileList = null;

        //压缩按钮事件
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            //执行压缩操作
            if (FileList != null && FileList.Length > 0)
            {
                button2.IsEnabled = false;

                //执行压缩操作
                Compress();
                button2.IsEnabled = true;
                MessageBox.Show("压缩完成");
            }
        }
        private void Compress()
        {
            foreach (var item in FileList)
            {
                string fileName = item;
                //判断文件是否还存在
                if (File.Exists(fileName))
                {
                    //读取文件内容
                    string scource = File.ReadAllText(item);
                    JavaScriptCompressor compressor = new JavaScriptCompressor();
                    scource = compressor.Compress(scource);
                    //写入文件
                    if (checkOne.IsChecked == true)
                    {
                        FileInfo info = new FileInfo(fileName);
                        fileName = info.DirectoryName + "\\" + info.Name.Replace(".js", ".min.js");
                    }
                    File.WriteAllText(fileName, scource);
                }
            }
        }
        //拖入
        private void Window_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effects = DragDropEffects.Link;
            else
                e.Effects = DragDropEffects.None;
        }
        //松开
        private void Window_Drop(object sender, DragEventArgs e)
        {
            Array result = (System.Array)e.Data.GetData(DataFormats.FileDrop);
            if (result != null && result.Length > 0)
            {
                //获取第一个文件夹
                string temppath = result.GetValue(0).ToString();
                if (Directory.Exists(temppath))
                {
                    txtFile.Text = temppath;
                    //读取文件夹中的文件.css文件
                    FileList = Directory.GetFiles(temppath, "*.js");
                    listOne.ItemsSource = FileList;
                }
                else
                {
                    MessageBox.Show("文件夹不存在");
                }
            }
        }
    }
}
